import type { IStack, ObjStack } from "../../types";

/**
 * @description: 使用对象模拟栈;LIFO;时间复杂度O(1)
 * @author hzq
 * @date 2025-4-10 09:54:00
 */
class Stack<T> implements IStack<T> {
  private items: ObjStack<T>;
  private count: number;
  constructor() {
    this.items = {};
    this.count = 0;
  }

  isEmpty() {
    return this.count === 0;
  }

  size() {
    return this.count;
  }

  clear() {
    this.items = {};
    this.count = 0;
  }

  pop() {
    if (this.isEmpty()) return void 0;
    this.count--;
    const result = this.items[this.count];
    delete this.items[this.count];
    return result;
  }

  peek() {
    if (this.isEmpty()) return void 0;
    return this.items[this.count - 1];
  }

  push(...args: T[]) {
    args.forEach((i) => {
      this.items[this.count] = i;
      this.count++;
    });
  }

  toString() {
    if (this.isEmpty()) return null;
    return `Stack:[${this.items[this.count - 1]},...rest]`;
  }
}

export default Stack;
